import typing as t

from flask import request, jsonify
from flask.views import MethodView
from flask_pydantic import validate
from pydantic import BaseModel, Field

from common.utils.http import fail_api, success_api, table_api
from extensions import db
from models import MelonModel, RoleModel


def delete_by_id(_id):
    """ 删除用户 """
    res = MelonModel.query.filter_by(id=_id).delete()
    db.session.commit()
    return res


def batch_remove_melon():
    ids = request.form.getlist('ids[]')
    """ 批量删除 """
    for _id in ids:
        delete_by_id(_id)
    return success_api(message="批量删除成功")


def update_melon_role(_id, roles_list):
    melon = MelonModel.query.filter_by(id=_id).first()
    roles_id = []
    for role in melon.role:
        roles_id.append(role.id)
    roles = RoleModel.query.filter(RoleModel.id.in_(roles_id)).all()
    for r in roles:
        melon.role.remove(r)
    roles = RoleModel.query.filter(RoleModel.id.in_(roles_list)).all()
    for r in roles:
        melon.role.append(r)
    db.session.commit()


def melons_delete():
    """批量删除"""
    ids = request.form.getlist('ids[]')
    batch_remove(ids)
    return success_api(message="批量删除成功")


class QueryModel(BaseModel):
    page: int = 1
    limit: int = 10
    name: t.Optional[str] = Field(alias='name')
    type: t.Optional[str] = Field(alias='type')
    origin: t.Optional[str] = Field(alias='origin')
    comment: t.Optional[str] = Field(alias='comment')


class PersonModel(BaseModel):
    role_ids: str = Field(alias='roleIds')
    melonname: str
    real_name: str = Field(alias='realName')
    password: str


class MelonModel2(BaseModel):
    name: str = Field(alias='name')
    type: str = Field(alias='type')
    origin: str = Field(alias='origin')
    comment: str = Field(alias='comment')


class MelonModel3(BaseModel):
    id: int = Field(alias='id')
    name: str = Field(alias='name')
    type: str = Field(alias='type')
    origin: str = Field(alias='origin')
    comment: str = Field(alias='comment')


class MelonApi(MethodView):
    """修改用户数据"""

    @validate()
    def get(self, _id, query: QueryModel):

        filters = []

        if query.name:
            filters.append(MelonModel.name.like('%' + query.name + '%'))
        if query.origin:
            filters.append(MelonModel.origin.like('%' + query.origin + '%'))

        paginate = MelonModel.query.filter(
            *filters).paginate(
            page=query.page, per_page=query.limit, error_out=False)

        melon_data = [{
            'id': item.id,
            'name': item.name,
            'type': item.type,
            'origin': item.origin,
            'comment': str(item.comment),
        } for item in paginate.items]
        return table_api(
            result={
                'items': melon_data,
                'total': paginate.total,
            }
            , code=0
        )

    @validate()
    def post(self, body: MelonModel2):
        """新建单个用户"""
        melon = MelonModel()
        melon.name = body.name
        melon.type = body.type
        melon.origin = body.origin
        melon.comment = body.comment
        db.session.add(melon)
        db.session.commit()
        return success_api(message="增加成功", code=0)


def updateLemonById(_id):
    name = request.json.get('name', '')
    melon_type = request.json.get('type', '')
    origin = request.json.get('origin', '')
    comment = request.json.get('comment', '')
    # 更新用户数据
    MelonModel.query.filter_by(id=_id).update({'name': name,
                                               'type': melon_type,
                                               'origin': origin,
                                               'comment': comment})
    db.session.commit()
    return success_api(message="更新成功")


def deleteLemonById(_id):
    # 删除用户
    print(_id)
    res = delete_by_id(_id)
    if not res:
        return fail_api(message="删除失败")
    return success_api(message="删除成功")
